package com.acme.domain.email;

import java.util.LinkedList;
import java.util.List;

public class Queue<T> {

	private List<T> queue = new LinkedList<T>();
	private final int NUMBER_OF_ELEMENTS = 5;
	
	private boolean isClosed = false;
	
	
	public  T getEmail() throws InterruptedException {
		synchronized(queue){
			while( queue.isEmpty() && !isClosed){
				System.out.println("waiting");
				queue.wait();
			}
			System.out.println("removed");
			try {
				return queue.remove(0);
			} catch (IndexOutOfBoundsException ex){
				throw new IllegalStateException( "Queue closed while getEmail thread waiting");
			}
		}
	}

	public void addEmail(T email) throws InterruptedException {
		synchronized(queue){
			if ( queue.size() >= NUMBER_OF_ELEMENTS ){
				System.out.println("full");
				queue.wait();
			}
			if (isClosed) {
				return;
			} else {
				queue.add(email);
				System.out.println("added");
				queue.notifyAll();
			}
		}
	}

	public boolean isEmpty(){
		return queue.isEmpty();
	}

	public boolean isClosed() {
		return isClosed;
	}
	
	public void close(){
		synchronized (queue) {
			isClosed = true;
			queue.notifyAll();		
		}
	}
	
}
